package com.designpattern.observer;

import java.util.ArrayList;
import java.util.List;

public class ObserverTest {
    public static void main(String[] args) {
        Suject suject = new Suject();

        Observer observer1=new Task1();
        Observer observer2=new Task2();

        suject.addObserver(observer1);
        suject.addObserver(observer2);
        suject.notifyObserver("哈哈");
    }
}

class Suject{
    //容器
    List<Observer> container=new ArrayList<>();
    //add
    public void addObserver(Observer observer){
        container.add(observer);
    }
    //remove
    public void removeObserver(Observer observer){
        container.remove(observer);
    }

    public void notifyObserver(Object object){
        container.forEach(s->{
            s.update(object);
        });
    }
}

interface Observer{
    void update(Object object);
}

class Task1 implements Observer{

    @Override
    public void update(Object object) {
        System.out.println("Task1 received:"+object);
    }
}

class Task2 implements Observer{

    @Override
    public void update(Object object) {
        System.out.println("Task2 received:"+object);
    }
}
